/*********************************************************
 * CS 252 Project 6
 * Android VOIP App
 * 
 * RingerClient Class
 * 
 * This class establishes a connection with the
 * RingerServer class
 *********************************************************/

package com.avp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.util.Log;

public class RingerClient {
	String _user;
	int _port;
	Socket _socket;
	BufferedReader _in;
	PrintWriter _out;
	boolean _connected;
	String _reply;
	Voice voice;
	
	//////////////////
	// Constructors //
	//////////////////
	public RingerClient(String user, int port) {
		_user = user;
		_port = port;
		_connected = false;
	}
	
	/////////////
	// Methods //
	/////////////
	public void call(String ringerServerIP, int destinationPort) {
		try {
			InetAddress serverAddress = InetAddress.getByName(ringerServerIP);
			_socket = new Socket(serverAddress, destinationPort);
			
			_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
			_out = new PrintWriter(_socket.getOutputStream(), true);
			
			//make the call
			_out.println("Calling");
			_out.println(_user);
			
			//wait for accept or reject responses
			String response = null;
			while(response == null) {
				response = _in.readLine();
			}
			Log.d("ring", "response"+response);
			if (response.equals("accept")) {
				_connected = true;
				voice = new Voice();
				Log.d("ring", "sent call");
				
				voice.startConnection(_socket.getInetAddress(),8999);
				
			} else if (response.equals("reject")) {
				endCall();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void endCall() {
		_out.println("End Call");
		closeAll();
	}
	
	//close all current connections
	public void closeAll() {
		try {
			if (voice!=null)
			voice.stopConnection();
			_socket.close();
			_in.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
